<template>
  <el-dialog title="编辑弹层" :visible="showDialog" @before-close="btnCancel">
    <el-form
      ref="roleForm"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="formData.description" />
      </el-form-item>
    </el-form>
    <!-- 底部 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { editRoleAPI, addRoleAPI } from '@/api/settings.js'

export default {
  props: {
    showDialog: {
      default: false,
      type: Boolean
    }, // 状态
    formData: {
      type: Object,
      required: true
    } // 表单数据
  },
  data() {
    return {
      rules: {
        name: [],
        description: []
      } // 表单校验规则
    }
  },
  methods: {
    // 取消操作
    btnCancel() {
      this.$message.info('取消操作')
      this.resetFn()
    },
    // 提交按钮
    async btnOK() {
      const { id } = this.formData
      // 有 id 为修改，无则新增
      id
        ? await editRoleAPI(id, this.formData)
        : await addRoleAPI(this.formData)
      this.$message.success('操作成功')
      this.resetFn()
      this.$emit('reload')
    },
    // 重置操作
    resetFn() {
      this.$refs.roleForm.resetFields() // 重置表单
      this.$emit('update:show-dialog', false) // 关闭弹层
    }
  }
}
</script>
